home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_04 / gage / expand2.c < prev   
C/C++ Source or Header  |  1994-02-16  |  2KB  |  80 lines

  1. /* expand.c */
  2.  
  3. #include <stdio.h>
  4.  
  5. /* Decompress data from input to output */
  6. void expand (FILE *input, FILE *output)
  7. {
  8.   unsigned char left[256], right[256], stack[30];
  9.   short int c, count, i, size;
  10.  
  11.   /* Unpack each block until end of file */
  12.   while ((count = getc(input)) != EOF) {
  13.  
  14.     /* Set left to itself as literal flag */
  15.     for (i = 0; i < 256; i++)
  16.       left[i] = i;
  17.  
  18.     /* Read pair table */
  19.     for (c = 0;;) {
  20.  
  21.       /* Skip range of literal bytes */
  22.       if (count > 127) {
  23.         c += count - 127;
  24.         count = 0;
  25.       }
  26.       if (c == 256) break;
  27.  
  28.       /* Read pairs, skip right if literal */
  29.       for (i = 0; i <= count; i++, c++) {
  30.         left[c] = getc(input);
  31.         if (c != left[c])
  32.           right[c] = getc(input);
  33.       }
  34.       if (c == 256) break;
  35.       count = getc(input);
  36.     }
  37.  
  38.     /* Calculate packed data block size */
  39.     size = 256 * getc(input);
  40.     size += getc(input);
  41.  
  42.     /* Unpack data block */
  43.     for (i = 0;;) {
  44.  
  45.       /* Pop byte from stack or read byte */
  46.       if (i)
  47.         c = stack[--i];     
  48.       else {
  49.         if (!size--) break;
  50.         c = getc(input);
  51.       }
  52.  
  53.       /* Output byte or push pair on stack */
  54.       if (c == left[c])      
  55.         putc(c,output);
  56.       else {
  57.         stack[i++] = right[c];
  58.         stack[i++] = left[c];
  59.       }
  60.     }
  61.   }
  62. }
  63.  
  64. void main (int argc, char *argv[])
  65. {
  66.   FILE *infile, *outfile;
  67.  
  68.   if (argc != 3)
  69.     printf("Usage: expand infile outfile\n");
  70.   else if ((infile=fopen(argv[1],"rb"))==NULL)
  71.     printf("Error opening input %s\n",argv[1]);
  72.   else if ((outfile=fopen(argv[2],"wb"))==NULL)
  73.     printf("Error opening output %s\n",argv[2]);
  74.   else {
  75.     expand(infile,outfile);
  76.     fclose(outfile);
  77.     fclose(infile);
  78.   }
  79. }
  80.